package com.demodis.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.demodis.dao.PermissionDaoI;
import com.demodis.dao.RoleDaoI;
import com.demodis.dao.impl.PermissionDaoImpl;
import com.demodis.dao.impl.RoleDaoImpl;
import com.demodis.domain.TblPermission;
import com.demodis.domain.TblRole;
import com.demodis.service.RoleServiceI;
import com.demodis.util.Utils;

public class RoleServiceImpl implements RoleServiceI {

	RoleDaoI roleDao = new RoleDaoImpl();
	PermissionDaoI permDao = new PermissionDaoImpl();

	@Override
	public Object getRoles() {
		List<TblRole> listRole = roleDao.getRoles();
		List<TblPermission> listPerm = permDao.getPermissions();
		Map<String, Object> map = new HashMap<String, Object>();

		for (TblRole role : listRole) {
			StringBuilder permNames = new StringBuilder();
			StringBuilder ids = new StringBuilder();
			int rolePermValue = role.getRolePermValue();
			if (rolePermValue > 0) {
				for (TblPermission perm : listPerm) {
					if (Utils.existPerm(rolePermValue, perm.getPermValue())) {
						if (permNames.toString().length() == 0) {
							permNames.append(perm.getPermName());
							ids.append(perm.getPermId());
						} else {
							permNames.append("," + perm.getPermName());
							ids.append("," + perm.getPermId());
						}
					}
				}
				role.setPermNames(permNames.toString());
				role.setIds(ids.toString());
			}
		}

		map.put("total", listRole.size());
		map.put("rows", listRole);
		return map;
	}

	@Override
	public boolean save(TblRole role) {
		return roleDao.save(role);
	}

	@Override
	public boolean modify(TblRole role) {
		return roleDao.modify(role);
	}

	@Override
	public boolean delete(TblRole role) {
		return roleDao.delete(role);
	}

	@Override
	public Object getRoleComboBoxData() {
		return roleDao.getRoles();
	}

	@Override
	public boolean distribute(TblRole role) {
		return roleDao.distribute(role);
	}

}
